package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"gitee.com/captials-team/ubdframe/src/domain/dto/amap"
	"gitee.com/captials-team/ubdframe/src/pkg/logs"
	"io"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

var flagKey = flag.String("key", "", "高德地图API的应用key")
var flagMaxLevel = flag.Int("max-level", 4, "最大查询行政等级，默认=4，1=中国，2=省，3=市，4=区")

func main() {
	flag.Parse()

	var list []string
	err := queryDistrict("", 1, func(item dto.RegionItem) {
		s := dto.EncodeRegionItem(item)

		list = append(list, s)
		logs.Out.Info("%s%s", strings.Repeat("\t", (item.Level-1)*3), s)
	})
	common.ErrPanic(err)

	//保存入csv
	err = os.WriteFile(fmt.Sprintf("./regions.%s.csv", time.Now().Format("20060102150405")), []byte(strings.Join(list, "\n")), os.ModeAppend)
	common.ErrPanic(err)
}

func queryDistrict(adCode string, level int, f func(dto.RegionItem)) error {

	if f == nil {
		return nil
	}
	if level >= *flagMaxLevel {
		return nil
	}
	time.Sleep(time.Second * 1)
	r, err := queryDistrictForLevel(amap.DistrictApiQuery{
		Keywords:    adCode,
		SubDistrict: 1,
		Offset:      100,
	})
	common.ErrPanic(err)
	if r.Count == "0" {
		return nil
	}

	for _, v := range r.Districts {
		if adCode == "" {
			f(dto.RegionItem{
				Name:       v.Name,
				Code:       v.AdCode,
				ParentCode: adCode,
				Level:      level,
				LevelName:  v.Level,
			})
		}

		for _, v1 := range v.Districts {
			//logs.Out.Info("%s %s-%s", strings.Repeat("\t", level*3), v1.Name, v1.AdCode)
			f(dto.RegionItem{
				Name:       v1.Name,
				Code:       v1.AdCode,
				ParentCode: v.AdCode,
				Level:      level + 1,
				LevelName:  v1.Level,
			})
			err1 := queryDistrict(v1.AdCode, level+1, f)
			common.ErrPanic(err1)
		}
	}
	return nil
}

func queryDistrictForLevel(query amap.DistrictApiQuery) (amap.DistrictApiResp, error) {
	query.Key = *flagKey

	if query.Key == "" {
		return amap.DistrictApiResp{}, fmt.Errorf("amap key empty")
	}

	req, err := http.NewRequest(http.MethodGet, amap.DistrictQueryAPI, nil)
	if err != nil {
		return amap.DistrictApiResp{}, err
	}

	data := url.Values{}
	data.Set("key", query.Key)
	data.Set("keywords", query.Keywords)
	if query.Page > 0 {
		data.Set("page", fmt.Sprintf("%d", query.Page))
	}
	if query.Offset > 0 {
		data.Set("offset", fmt.Sprintf("%d", query.Offset))
	}
	if query.Output != "" {
		data.Set("output", query.Output)
	}
	data.Set("subdistrict", fmt.Sprintf("%d", query.SubDistrict))

	req.URL.RawQuery = data.Encode()
	//logs.Out.Info("URL=%s", req.URL)

	c := &http.Client{
		Timeout: time.Second * 3,
	}
	tmp, err := c.Do(req)
	if err != nil {
		return amap.DistrictApiResp{}, err
	}
	defer tmp.Body.Close()

	s, err := io.ReadAll(tmp.Body)
	common.ErrPanic(err)
	//logs.Out.Info("%s", string(s))

	var resp amap.DistrictApiResp
	json.Unmarshal(s, &resp)

	if resp.Status != "1" {
		//logs.Out.Error("response fail: %s,%s", resp.Status, resp.Info)
		return resp, fmt.Errorf("response fail: %s,%s", resp.Status, resp.Info)
	}
	return resp, nil
}
